package com.zhang.core;

import com.zhang.constant.Constant;
import com.zhang.util.FileUtils;
import com.zhang.util.HttpUtils;
import com.zhang.util.LogUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 分块下载任务
 */
public class DownloadTask implements Callable<Boolean> {
    /**
     * 下载链接
     */
    private String url;
    /**
     * 起始位置
     */
    private Long startPos;
    /**
     * 结束位置
     */
    private Long endPos;
    /**
     * 分块
     */
    private int part;
    /**
     * 线程计数器
     */
    private CountDownLatch countDownLatch;
    public DownloadTask(String url, Long startPos, Long endPos, int part, CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {
        String httpFileName = HttpUtils.getHttpFileName(url);
        //分块拼接
        httpFileName = httpFileName + ".temp" + part;
        httpFileName = Constant.PATH + httpFileName;

        //获取下载链接
        HttpURLConnection httpFileSegmentation = HttpUtils.getHttpFileSegmentation(url, startPos, endPos);

        try (
                InputStream inputStream = httpFileSegmentation.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(inputStream);
                RandomAccessFile faf = new RandomAccessFile(httpFileName,"rw");
        ) {
            //下载
            int length = -1;
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            while ((length = bis.read(buffer)) != -1){
                //下载信息累加 （原子类的累加)
                DownloadInfoThread.downSize.add(length);
                faf.write(buffer,0,length);
            }
        } catch (FileNotFoundException e) {
            LogUtils.error("下载的文件不存在{}", url);
            return false;
        } catch (Exception e) {
            LogUtils.error("下载错误，请重试！");
            return false;
        }finally {
            httpFileSegmentation.disconnect();
            //执行结束，计数器减1
            countDownLatch.countDown();
        }

        return true;
    }
}
